package com.taotao.anno.sg;

import com.google.auto.service.AutoService;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@AutoService(Processor.class)
public class SerialVersionUIDProcessor extends AbstractProcessor {


    @Override
    public Set<String> getSupportedAnnotationTypes() {
        // 与注解 @SupportedAnnotationTypes({"com.taotao.anno.sg.GenerateSerialVersionUID"})  功能相同
        return new HashSet<>(Arrays.asList(GenerateSerialVersionUID.class.getName()));
    }


    @Override
    public SourceVersion getSupportedSourceVersion() {
        //设置为能够支持最新版本   @SupportedSourceVersion 等效
        return SourceVersion.latestSupported();
    }


    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
//        System.out.printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GenerateSerialVersionUID");
//        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GenerateSerialVersionUID");
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>GenerateSerialVersionUID");
        for (TypeElement annotation : annotations) {
            for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
                if (element instanceof TypeElement) {
                    TypeElement typeElement = (TypeElement) element;
                    generateSerialVersionUID(typeElement);
                }
            }
        }
        return true;
    }

    private void generateSerialVersionUID(TypeElement typeElement) {
        try {
            // 计算serialVersionUID (这里简化为随机UUID的hashCode)
            long serialVersionUID = UUID.randomUUID().hashCode() & 0x7FFFFFFFFFFFFFFFL;

            // 创建字段源代码
            String code = String.format("private static final long serialVersionUID = %dL;", serialVersionUID);

            // 使用Filer生成或修改源文件
            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    "Generating serialVersionUID for " + typeElement.getQualifiedName() + ": " + code);

            // 这里实际应该使用JavaPoet或其他库来修改源文件
            // 由于Java注解处理器的限制，直接修改源文件比较复杂
            // 更完整的实现可能需要使用AST修改工具

        } catch (Exception e) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Failed to generate serialVersionUID: " + e.getMessage());
        }
    }
}